package com.example.yorkfeng.bledemo;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "MainActivity";

    private TextView tvBleState;
    public static TextView tvReceive;
    private EditText etSend;

    private BluetoothLeClass mBle;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGattCharacteristic myGattCharacteristic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        findViewById(R.id.traceroute_rootview).setOnClickListener(this);

        findViewById(R.id.btnSend).setOnClickListener(this);

        tvBleState = (TextView) findViewById(R.id.tvBleState);
        tvReceive = (TextView) findViewById(R.id.tvRecevie);
        etSend = (EditText) findViewById(R.id.etSend);

        // Use this check to determine whether BLE is supported on the device.  Then you can
        // selectively disable BLE-related features.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        //开启蓝牙
        mBluetoothAdapter.enable();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mBluetoothAdapter.enable();

        mBle = new BluetoothLeClass(this);
        if (!mBle.initialize()) {
            Log.e(TAG, "Unable to initialize Bluetooth");
            finish();
        }

        if (mBle.deviceName == null){
            tvBleState.setText("蓝牙未连接");
        }else {
            tvBleState.setText("已链接:" + mBle.deviceName);

            myGattCharacteristic = mBle.myGattCharacteristic;
            //接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
            mBle.setCharacteristicNotification(myGattCharacteristic, true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(this, DeviceScanActivity.class);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.traceroute_rootview:
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;

            case R.id.btnSend:
                if (mBle.deviceName == null){
                }else {
                    myGattCharacteristic.setValue(String.valueOf(etSend.getText())+"\r\n");
                    mBle.writeCharacteristic(myGattCharacteristic);
                }
                break;
        }
    }
}
